function isLocalIP(ip) {
  // 检查IP地址是否是内网地址
  // 排除私有地址范围
  if (
      /^10\./.test(ip) || // 10.x.x.x
      /^192\.168\./.test(ip) || // 192.168.x.x
      /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(ip) // 172.16.x.x - 172.31.x.x
  ) {
    return true
  }

  // 排除保留地址
  if (
      /^127\./.test(ip) || // 127.x.x.x (loopback)
      /^169\.254\./.test(ip) // 169.254.x.x (link-local)
      // 还可以添加其他保留地址的检查，如多播地址等
  ) {
    return true
  }
  if (ip.length > 15) {
    return true
  }
  // 其他条件下认为是公网地址
  return false
}
// rtmp://gwm-000-cn-0448.bcloud365.net:9016/talk_2e24b0d33c27886b/Mnx8Y2U3ZTg2YmYxOGZmZTE3YmQ0NDRkZWUxMTcyN2FjZTd8fDJlMjRiMGQzM2MyNzg4NmJ8fDYwOTJlNTg5OWNjODIzOTYzYjg5OWZjNDg12NTdiNmNiOThiOWQ1NDkyYzY5MDA0OTlmNDc4ZjVkMzgzMDNiODJ8fHJ0bXB8fDE3MTQwMzYzNDk0Nzh8fDE3MTQwNzIzNDkzMjd8fEdXTQ%3D%3D.376a8ab00c48614ed6326b3d2bc211d9
export const twoWayVideoWebrtc = {
  data() {
    return {

      // 双向视频对讲
      talkUrlInput: '',
      sn: '',
      // 	webrtc相关
      hasLocalIP: '',
      candidateSDP: '',
      localSDP: '',
      iceCandidateCount: 0,
      iceCandidateCountOK: 0,
      frameRate: 12,
      pcTalk: new RTCPeerConnection({
        encodings: [
          {maxBitrate: 2000 * 1000, maxFramerate: this.frameRate, scaleResolutionDownBy: 1.0} // 第一个编码配置，设置最大比特率和不进行分辨率缩放
          //{ maxBitrate: 1000000, scaleResolutionDownBy: 2.0 }, // 第二个编码配置，设置最大比特率和将分辨率缩放为原来的一半
          //{ maxBitrate: 500000, scaleResolutionDownBy: 4.0 }   // 第三个编码配置，设置最大比特率和将分辨率缩放为原来的四分之一
        ],
        iceServers: [{
          urls: ['stun:stun.voipbuster.com:3478'] //stun:stun.oss.aliyuncs.com:3478
        }]
      }),
      remoteVideo:null,
      localVideo:null,
    }
  },
  onShow(){
  },
  onLoad(opt) {
  },
  methods: {
    initWebRtc() {
      let _that = this
      _that.pcTalk.ontrack = function (event) {
        if (!_that.remoteVideo) {
          _that.remoteVideo = document.getElementsByTagName('video')[0];//
        }
        if (_that.remoteVideo && event.streams && event.streams.length > 0) {
          let eventStream = event.streams[0];
          eventStream.getTracks().forEach(track => {
            if (track.kind === 'audio') {
              console.log('This is an audio track', event.streams.length);
            } else if (track.kind === 'video') {
              console.log('This is a video track', event.streams.length);
            }
          })
          _that.remoteVideo.srcObject = eventStream;
        } else {
          console.log('pcTalk wait stream track finish');
        }
      };
    },
    GetTalkUrl() {
      if (this.getTalkUrlInput === '')
      {
        return;
      }
      let xhrGet = new XMLHttpRequest();
      xhrGet.open('POST', this.getTalkUrlInput, true);
      xhrGet.setRequestHeader("Accessol-Allow-Origin","*");
      let _that = this
      xhrGet.onreadystatechange = function() {
        if (xhrGet.readyState === XMLHttpRequest.DONE) {
          if (xhrGet.status === 200) {
            // 收到服务器响应，连接仍然活跃
            let data = xhrGet.responseText;
            let jsonstr = JSON.parse(data)
            console.log('GetPlayUrl successfully',jsonstr);
            _that.talkUrlInput = jsonstr.retMsg;
          } else {
            // 连接出现问题，处理断开连接的逻辑sendTalkHeartbeat
            console.log('GetTalkUrl err,code:'+xhr.status+' msg:'+xhr.statusText);
            alert('GetTalkUrl err,code:'+xhr.status+' msg:'+xhr.statusText);
          }
        }
      };
      xhrGet.send();
    },
    setTalkEnable() {
      let _that = this
      let talkURL = this.talkUrlInput;
      this.pcTalk.onicecandidate = function (event) {
        _that.handleCandidate(event, talkURL);
      };
      this.pcTalk.onicecandidateerror = function (event) {
        //console.log('onicecandidateerror');
      };
      this.pcTalk.onconnectionstatechange = function (event) {
        console.log('对讲状态==>', event.currentTarget.connectionState);
      };
      //音视频对讲
      navigator.mediaDevices.getUserMedia({
        video: {
          width: 240,//宽高和实际出流的相反
          height: 320,
          frameRate: {ideal: this.frameRate, max: this.frameRate},//就算设置25，webrtc rtp时间戳间隔还是按照30的帧率
          facingMode: 'user',//前置摄像头facingMode: user ,'environment'表示要使用后置摄像头
          // 设置I帧间隔为60（大多数浏览器仅支持设置I帧间隔）
          video: {mandatory: {maxKeyFrameInterval: 60}}
        }, audio: true
      }).then(function (stream) {
        console.log('getUserMedia audio video');
        if (!_that.localVideo) {
          _that.localVideo = document.getElementsByTagName('video')[1];//
        }
        _that.localVideo.srcObject = stream;
        _that.pcTalk.addTransceiver(stream.getAudioTracks()[0], {direction: 'sendrecv'});//
        _that.pcTalk.addTransceiver(stream.getVideoTracks()[0], {direction: 'sendrecv'});//音视频对讲
        let senders = _that.pcTalk.getSenders();
        // 获取当前编码参数
        // 遍历发送器列表
        senders.forEach(sender => {
          // 获取发送器的编码参数
          if (sender.track.kind === 'video') {
            let parameters = sender.getParameters();
            // 获取编码器参数中的最大比特率
            if (parameters.encodings && parameters.encodings.length > 0) {
              console.log('sender.getParameters: ' + parameters.degradationPreference + 'maxFramerate' + parameters.encodings[0].maxFramerate + 'maxBitrate' + parameters.encodings[0].maxBitrate);
              parameters.degradationPreference = "maintain-framerate";
              //parameters.encodings[0].maxTemporalLayer = 2;// 属性设置为2，您可以将I帧间隔设置为50
              //parameters.encodings[0].maxKeyFrameDistance=60;
              parameters.encodings[0].maxFramerate = _that.frameRate;//30
              // 设置最大比特率为500000 bps（即1000kbps）
              parameters.encodings[0].maxBitrate = 200000;
              // 应用更新的编码参数
              //sender.setParameters(parameters);
              //console.log('sender.setParameters: ' + parameters.encodings[0].maxTemporalLayer+'maxFramerate'+parameters.encodings[0].maxFramerate+'maxBitrate'+parameters.encodings[0].maxBitrate);
            }
          }
        });
        _that.SetTalkLocalOffer();
      })
          .catch(function (error) {
            console.log('getUserMedia audio video err', error);
          });

    },
    setTalkDisable() {
      console.log('stopTalk');
      this.pcTalk.close();
      this.pcTalk = new RTCPeerConnection({
        iceServers: [{
          urls: ['stun:stun.voipbuster.com:3478'] //stun:stun.oss.aliyuncs.com:3478
        }]
      })
      this.localVideo.srcObject = null;
      this.initWebRtc()
      //pcTalk = null;//不注释会报错
      this.stopTalkButton = true;
      this.startTalkButton = false;
    },
    SetTalkLocalOffer() {
      this.pcTalk.createOffer().then(desc => {
        console.log('pcTalk.createOffer');
        this.pcTalk.setLocalDescription(desc).then(() => {
          //console.log('pcTalk.setLocalDescription',desc.sdp);
          this.localSDP = desc.sdp;
        });
      }).catch(e => {
        console.log(e);
      });
      this.stopTalkButton = false
      this.startTalkButton = true
    },
    doCall(param,url)
    {
      this.TalkNegotiateSDP(param,url);
    },
    TalkNegotiateSDP(param,url)//因为要创建一个新的http链接，所以需要新的函数
    {
      let json = {
        "action":"offer",
        "sdp":param,
        "FrameRate":this.frameRate
      }
      let _that = this
      //var jsonStr = JSON.stringify(json);
      //console.log(jsonStr)
      let playUrl = url
      //var playUrl = "https://139.9.149.150:9031/testTalk/202404h264g711a.flv.webrtc"//暂时使用9031这样不同的端口代理实现不复用一个socket
      let xhrTalk=new XMLHttpRequest();//这样还是对讲和预览还是会复用一个socket，会导致服务出错，除非修改服务架构，根据不同的url创建不同的session
      xhrTalk.onreadystatechange = function(){
        console.log('xhrTalk readyState',xhrTalk.readyState);
        if(xhrTalk.readyState==4){
          if(xhrTalk.status==200||xhrTalk.status==304){
            let data = xhrTalk.responseText;
            let jsonstr = JSON.parse(data)
            console.log(jsonstr);
            let anwser = {};
            anwser.sdp = jsonstr.sdp;
            anwser.type = 'answer';
            console.log('answer:', jsonstr.sdp);
            _that.pcTalk.setRemoteDescription(anwser).then(() => {
              console.log('TalkNegotiateSDP pc set remote sucess');
              // 每隔30秒发送一次心跳请求
              //setInterval(sendTalkHeartbeat, 30000)
              _that.GetTalkStatus();//一次就够，维持长链接
            }).catch(e => {
              console.log( e);
            });
          }
        }
      }
      xhrTalk.open("POST",playUrl,true);
      //如果是POST请求方式，设置请求首部信息
      xhrTalk.setRequestHeader("Content-type","application/json; charset=utf-8");
      //xhrTalk.setRequestHeader("Connection","Keep-Alive");
      xhrTalk.setRequestHeader("Access-Control-Allow-Headers","Access-Control-Allow-Origin, ClientType,Accept-Encoding,Content-Type,Access-Token,Authorization,authorization,Token,Tag,Cache-Control");
      xhrTalk.setRequestHeader("Accessol-Allow-Origin","*");
      let jsonStr = JSON.stringify(json);
      xhrTalk.send(jsonStr);
    },
    GetTalkStatus()
    {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', this.talkUrlInput, true);
      xhr.setRequestHeader("Accessol-Allow-Origin","*");
      xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status === 200||xhr.status === 204) {
            // 收到服务器响应，连接仍然活跃
            console.log('TalkStatus(exit) OK ,status:'+xhr.status+' msg:'+xhr.statusText);
          } else {
            // 连接出现问题，处理断开连接的逻辑sendTalkHeartbeat
            console.log('TalkStatus err,code:'+xhr.status+' msg:'+xhr.statusText);
          }
        }
      };
      xhr.send();
    },
    // 双向视频对讲webrtc
    handleCandidate(event, url) {
      if (event.candidate) {
        this.iceCandidateCount++; // 每收到一个候选都增加计数
        console.log('Remote ICE candidate: \r\n ' + event.candidate.candidate + '\r\niceCandidateCount' + this.iceCandidateCount);
        const candidateIP = event.candidate.candidate.split(' ')[4] // 提取ICE候选中的IP地址
        this.hasLocalIP = isLocalIP(candidateIP)
        if (!this.hasLocalIP) {//过滤掉无效的，比如.local这种会导致服务设置candidate失败
          if (this.candidateSDP) {
            this.candidateSDP += 'a=' + event.candidate.candidate + '\r\n'
          } else {
            this.candidateSDP = 'a=' + event.candidate.candidate + '\r\n'
          }
          this.iceCandidateCountOK++;
          if (this.iceCandidateCountOK === 1) {
            if (this.localSDP) {
              let searchStringAudio = 'm=audio';
              let indexAudio = this.localSDP.indexOf(searchStringAudio);
              let searchStringVideo = 'm=video';
              let indexVideo = this.localSDP.indexOf(searchStringVideo);
              let indexPos = 0;
              if (indexVideo > indexAudio) {
                indexPos = indexVideo;
              } else {
                indexPos = indexAudio;
              }
              this.localSDP = this.localSDP.substring(0, indexPos) + this.candidateSDP + this.localSDP.substring(indexPos);
            }
            //candidateSDP=null;
          }
          if (this.iceCandidateCountOK >= 2) {
            console.log('ICE negotiation finished. All ICE candidates have been done.', url);
            // // Send the candidate to the remote peer
            //this.localSDP.replace(/a=ice-options:trickle/g, '');
            let searchString = 'a=ice-options:trickle';
            if (this.localSDP) {
              let index = this.localSDP.indexOf(searchString);//去掉a=ice-options:trickle，candidate和sdp一起发
              this.localSDP = this.localSDP.substring(0, index) + this.localSDP.substring(index + searchString.length + 2);
              index = this.localSDP.indexOf(searchString);//去掉a=ice-options:trickle，candidate和sdp一起发
              this.localSDP = this.localSDP.substring(0, index) + this.localSDP.substring(index + searchString.length + 2);
              this.localSDP += this.candidateSDP;
              console.log('localSDP:', this.localSDP);
              // this.localSDP.includes('H264') ? (this.isH264 = '是') : (this.isH264 = '否')
              this.doCall(this.localSDP, url);
              this.candidateSDP = null;
              this.localSDP = null;
              this.iceCandidateCountOK = 0;
              this.iceCandidateCount = 0;
            } else {
              console.log('不支持webrtc')
            }
          }
        }
      }
    },
  }
}